using System.Windows.Forms;
using TeachingManagementSystem.BLL;
using TeachingManagementSystem.Models;

namespace TeachingManagementSystem.Forms.ScheduleManagement
{
    public partial class ScheduleEditForm : Form
    {
        private ScheduleBLL _scheduleBLL;
        private CourseBLL _courseBLL;
        private ClassroomBLL _classroomBLL;
        private UserBLL _userBLL;
        private Schedule _schedule;
        private bool _isEditMode;
        private User _currentUser;

        public ScheduleEditForm(Schedule schedule, User currentUser)
        {
            InitializeComponent();
            
            _scheduleBLL = new ScheduleBLL();
            _courseBLL = new CourseBLL();
            _classroomBLL = new ClassroomBLL();
            _userBLL = new UserBLL();
            _schedule = schedule;
            _isEditMode = schedule != null;
            _currentUser = currentUser;
            
            // 设置窗口属性
            this.WindowState = FormWindowState.Normal;
            this.Size = new System.Drawing.Size(800, 450);
            this.StartPosition = FormStartPosition.CenterScreen;
            
            // 初始化表单数据
            InitializeForm();
        }

        private void InitializeForm()
        {
            // 加载学期选项
            if (comboBoxSemester != null)
            {
                comboBoxSemester.Items.AddRange(new string[] { "2024-2025学年第一学期", "2024-2025学年第二学期", 
                    "2023-2024学年第一学期", "2023-2024学年第二学期" });
                comboBoxSemester.SelectedIndex = 0; // 默认选择第一个学期
            }

            // 加载星期选项
            if (comboBoxDayOfWeek != null)
            {
                comboBoxDayOfWeek.Items.AddRange(new string[] { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日" });
            }

            // 加载节次选项
            for (int i = 1; i <= 12; i++)
            {
                comboBoxStartSection.Items.Add(i);
            }
            
            // 设置节数控件的范围和默认值
            if (numericUpDownSectionCount != null)
            {
                numericUpDownSectionCount.Minimum = 1;
                numericUpDownSectionCount.Maximum = 12;
                numericUpDownSectionCount.Value = 1; // 设置默认值为1
            }

            // 加载课程
            LoadCourses();

            // 加载教室
            LoadClassrooms();

            // 加载教师
            LoadTeachers();

            if (_isEditMode)
            {
                // 编辑模式，填充表单
                this.Text = "编辑课表";
                if (_schedule != null)
                {
                    txtScheduleID.Text = _schedule.ScheduleID.ToString();
                    var course = _courseBLL.GetCourseByID(_schedule.CourseID);
                    if (course != null)
                    {
                        comboBoxCourse.SelectedItem = $"{course.CourseName} ({course.CourseCode})";
                    }
                    var teacher = _userBLL.GetUserByID(_schedule.TeacherID);
                    if (teacher != null)
                    {
                        comboBoxTeacher.SelectedItem = $"{teacher.FullName} (ID:{_schedule.TeacherID})";
                    }
                    var classroom = _classroomBLL.GetClassroomByID(_schedule.ClassroomID);
                    if (classroom != null)
                    {
                        comboBoxClassroom.SelectedItem = classroom.ClassroomNumber;
                    }
                    if (comboBoxDayOfWeek != null)
                    {
                        // 将DayOfWeek枚举转换为对应的中文星期
                        switch (_schedule.DayOfWeek)
                        {
                            case DayOfWeek.Monday:
                                comboBoxDayOfWeek.SelectedItem = "星期一";
                                break;
                            case DayOfWeek.Tuesday:
                                comboBoxDayOfWeek.SelectedItem = "星期二";
                                break;
                            case DayOfWeek.Wednesday:
                                comboBoxDayOfWeek.SelectedItem = "星期三";
                                break;
                            case DayOfWeek.Thursday:
                                comboBoxDayOfWeek.SelectedItem = "星期四";
                                break;
                            case DayOfWeek.Friday:
                                comboBoxDayOfWeek.SelectedItem = "星期五";
                                break;
                            case DayOfWeek.Saturday:
                                comboBoxDayOfWeek.SelectedItem = "星期六";
                                break;
                            case DayOfWeek.Sunday:
                                comboBoxDayOfWeek.SelectedItem = "星期日";
                                break;
                            default:
                                comboBoxDayOfWeek.SelectedItem = "星期一";
                                break;
                        }
                    }
                    if (comboBoxStartSection != null)
                        comboBoxStartSection.SelectedItem = _schedule.StartSection;
                    if (numericUpDownSectionCount != null)
                    {
                        // 确保SectionCount在有效范围内
                        decimal sectionCount = Math.Max((decimal)_schedule.SectionCount, numericUpDownSectionCount.Minimum);
                        sectionCount = Math.Min(sectionCount, numericUpDownSectionCount.Maximum);
                        numericUpDownSectionCount.Value = sectionCount;
                    }
                    if (comboBoxSemester != null)
                        comboBoxSemester.SelectedItem = _schedule.Semester ?? string.Empty;
                }
                btnSave.Text = "更新";
            }
            else
            {
                // 添加模式
                this.Text = "添加课表";
                txtScheduleID.Text = "自动生成";
                txtScheduleID.ReadOnly = true;
            }
        }

        private void LoadCourses()
        {
            var courses = _courseBLL.GetAllCourses();
            foreach (var course in courses)
            {
                comboBoxCourse.Items.Add($"{course.CourseName} ({course.CourseCode})");
            }
        }

        private void LoadClassrooms()
        {
            var classrooms = _classroomBLL.GetAllClassrooms();
            foreach (var classroom in classrooms)
            {
                comboBoxClassroom.Items.Add($"{classroom.ClassroomNumber}");
            }
        }

        private void LoadTeachers()
        {
            var teachers = _userBLL.GetUsersByRole(UserRole.Teacher);
            if (teachers != null && comboBoxTeacher != null)
            {
                foreach (var teacher in teachers)
                {
                    comboBoxTeacher.Items.Add($"{teacher.FullName} (ID:{teacher.UserID})");
                }

                // 如果是教师用户，默认选择自己
                if (_currentUser != null && _currentUser.Role == UserRole.Teacher)
                {
                    foreach (var item in comboBoxTeacher.Items)
                    {
                        if (item != null && item.ToString()?.Contains(_currentUser.UserID.ToString()) == true)
                        {
                            comboBoxTeacher.SelectedItem = item;
                            comboBoxTeacher.Enabled = false;
                            break;
                        }
                    }
                }
            }
        }

        private int GetSelectedCourseID()
        {
            if (comboBoxCourse?.SelectedItem != null)
            {
                string selectedText = comboBoxCourse.SelectedItem?.ToString() ?? string.Empty;
                // 查找课程代码部分
                int startIndex = selectedText.LastIndexOf("(") + 1;
                int endIndex = selectedText.LastIndexOf(")");
                if (startIndex > 0 && endIndex > startIndex)
                {
                    string courseCode = selectedText.Substring(startIndex, endIndex - startIndex);
                    var courses = _courseBLL?.GetAllCourses();
                    if (courses != null)
                    {
                        var course = courses.FirstOrDefault(c => c?.CourseCode == courseCode);
                        if (course != null)
                        {
                            return course.CourseID;
                        }
                    }
                }
            }
            return 0;
        }

        private int GetSelectedTeacherID()
        {
            if (comboBoxTeacher?.SelectedItem != null)
            {
                string selectedText = comboBoxTeacher.SelectedItem?.ToString() ?? string.Empty;
                int startIndex = selectedText.LastIndexOf("ID:") + 3;
                int endIndex = selectedText.LastIndexOf(")");
                if (startIndex > 0 && endIndex > startIndex)
                {
                    string idText = selectedText.Substring(startIndex, endIndex - startIndex);
                    if (int.TryParse(idText, out int teacherID))
                    {
                        return teacherID;
                    }
                }
            }
            return 0;
        }

        private int GetSelectedClassroomID()
        {
            if (comboBoxClassroom?.SelectedItem != null)
            {
                string selectedText = comboBoxClassroom.SelectedItem.ToString() ?? string.Empty;
                string classroomNumber = selectedText;
                var classrooms = _classroomBLL?.GetAllClassrooms();
                if (classrooms != null)
                {
                    var classroom = classrooms.FirstOrDefault(c => c?.ClassroomNumber == classroomNumber);
                    if (classroom != null)
                    {
                        return classroom.ClassroomID;
                    }
                }
            }
            return 0;
        }

        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();
            this.label7 = new System.Windows.Forms.Label();
            this.label8 = new System.Windows.Forms.Label();
            this.txtScheduleID = new System.Windows.Forms.TextBox();
            this.comboBoxCourse = new System.Windows.Forms.ComboBox();
            this.comboBoxTeacher = new System.Windows.Forms.ComboBox();
            this.comboBoxClassroom = new System.Windows.Forms.ComboBox();
            this.comboBoxDayOfWeek = new System.Windows.Forms.ComboBox();
            this.comboBoxStartSection = new System.Windows.Forms.ComboBox();
            this.numericUpDownSectionCount = new System.Windows.Forms.NumericUpDown();
            this.comboBoxSemester = new System.Windows.Forms.ComboBox();
            this.btnSave = new System.Windows.Forms.Button();
            this.btnCancel = new System.Windows.Forms.Button();
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            ((System.ComponentModel.ISupportInitialize)(this.numericUpDownSectionCount)).BeginInit();
            this.tableLayoutPanel1.SuspendLayout();
            this.SuspendLayout();
            // 
            // tableLayoutPanel1
            // 
            this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
            | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.tableLayoutPanel1.ColumnCount = 4;
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tableLayoutPanel1.Location = new System.Drawing.Point(20, 20);
            this.tableLayoutPanel1.Name = "tableLayoutPanel1";
            this.tableLayoutPanel1.RowCount = 5;
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 40F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 40F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 40F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 40F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 40F));
            this.tableLayoutPanel1.Size = new System.Drawing.Size(750, 200);
            this.tableLayoutPanel1.TabIndex = 18;
            this.tableLayoutPanel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
            // 
            // label1
            // 
            this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label1.Location = new System.Drawing.Point(3, 3);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(94, 34);
            this.label1.TabIndex = 0;
            this.label1.Text = "课表ID";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0);
            // 
            // label2
            // 
            this.label2.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label2.Location = new System.Drawing.Point(3, 43);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(94, 34);
            this.label2.TabIndex = 1;
            this.label2.Text = "课程";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.tableLayoutPanel1.Controls.Add(this.label2, 0, 1);
            // 
            // label3
            // 
            this.label3.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label3.Location = new System.Drawing.Point(3, 83);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(94, 34);
            this.label3.TabIndex = 2;
            this.label3.Text = "教师";
            this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.tableLayoutPanel1.Controls.Add(this.label3, 0, 2);
            // 
            // label4
            // 
            this.label4.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label4.Location = new System.Drawing.Point(3, 123);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(94, 34);
            this.label4.TabIndex = 3;
            this.label4.Text = "教室";
            this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.tableLayoutPanel1.Controls.Add(this.label4, 0, 3);
            // 
            // label5
            // 
            this.label5.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label5.Location = new System.Drawing.Point(3, 163);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(94, 34);
            this.label5.TabIndex = 4;
            this.label5.Text = "星期";
            this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.tableLayoutPanel1.Controls.Add(this.label5, 0, 4);
            // 
            // label6
            // 
            this.label6.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label6.Location = new System.Drawing.Point(380, 163);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(94, 34);
            this.label6.TabIndex = 5;
            this.label6.Text = "开始节次";
            this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.tableLayoutPanel1.Controls.Add(this.label6, 2, 4);
            // 
            // label7
            // 
            this.label7.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label7.Location = new System.Drawing.Point(380, 3);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(94, 34);
            this.label7.TabIndex = 6;
            this.label7.Text = "节数";
            this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.tableLayoutPanel1.Controls.Add(this.label7, 2, 0);
            // 
            // label8
            // 
            this.label8.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label8.Location = new System.Drawing.Point(380, 123);
            this.label8.Name = "label8";
            this.label8.Size = new System.Drawing.Size(94, 34);
            this.label8.TabIndex = 7;
            this.label8.Text = "学期";
            this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.tableLayoutPanel1.Controls.Add(this.label8, 2, 3);
            // 
            // txtScheduleID
            // 
            this.txtScheduleID.Dock = System.Windows.Forms.DockStyle.Fill;
            this.txtScheduleID.Location = new System.Drawing.Point(103, 3);
            this.txtScheduleID.Name = "txtScheduleID";
            this.txtScheduleID.Size = new System.Drawing.Size(271, 25);
            this.txtScheduleID.TabIndex = 8;
            this.txtScheduleID.ReadOnly = true;
            this.tableLayoutPanel1.Controls.Add(this.txtScheduleID, 1, 0);
            // 
            // comboBoxCourse
            // 
            this.comboBoxCourse.Dock = System.Windows.Forms.DockStyle.Fill;
            this.comboBoxCourse.FormattingEnabled = true;
            this.comboBoxCourse.Location = new System.Drawing.Point(103, 43);
            this.comboBoxCourse.Name = "comboBoxCourse";
            this.comboBoxCourse.Size = new System.Drawing.Size(271, 23);
            this.comboBoxCourse.TabIndex = 9;
            this.tableLayoutPanel1.Controls.Add(this.comboBoxCourse, 1, 1);
            // 
            // comboBoxTeacher
            // 
            this.comboBoxTeacher.Dock = System.Windows.Forms.DockStyle.Fill;
            this.comboBoxTeacher.FormattingEnabled = true;
            this.comboBoxTeacher.Location = new System.Drawing.Point(103, 83);
            this.comboBoxTeacher.Name = "comboBoxTeacher";
            this.comboBoxTeacher.Size = new System.Drawing.Size(271, 23);
            this.comboBoxTeacher.TabIndex = 10;
            this.tableLayoutPanel1.Controls.Add(this.comboBoxTeacher, 1, 2);
            // 
            // comboBoxClassroom
            // 
            this.comboBoxClassroom.Dock = System.Windows.Forms.DockStyle.Fill;
            this.comboBoxClassroom.FormattingEnabled = true;
            this.comboBoxClassroom.Location = new System.Drawing.Point(103, 123);
            this.comboBoxClassroom.Name = "comboBoxClassroom";
            this.comboBoxClassroom.Size = new System.Drawing.Size(271, 23);
            this.comboBoxClassroom.TabIndex = 11;
            this.tableLayoutPanel1.Controls.Add(this.comboBoxClassroom, 1, 3);
            // 
            // comboBoxDayOfWeek
            // 
            this.comboBoxDayOfWeek.Dock = System.Windows.Forms.DockStyle.Fill;
            this.comboBoxDayOfWeek.FormattingEnabled = true;
            this.comboBoxDayOfWeek.Location = new System.Drawing.Point(103, 163);
            this.comboBoxDayOfWeek.Name = "comboBoxDayOfWeek";
            this.comboBoxDayOfWeek.Size = new System.Drawing.Size(271, 23);
            this.comboBoxDayOfWeek.TabIndex = 12;
            this.tableLayoutPanel1.Controls.Add(this.comboBoxDayOfWeek, 1, 4);
            // 
            // comboBoxStartSection
            // 
            this.comboBoxStartSection.Dock = System.Windows.Forms.DockStyle.Fill;
            this.comboBoxStartSection.FormattingEnabled = true;
            this.comboBoxStartSection.Location = new System.Drawing.Point(480, 163);
            this.comboBoxStartSection.Name = "comboBoxStartSection";
            this.comboBoxStartSection.Size = new System.Drawing.Size(267, 23);
            this.comboBoxStartSection.TabIndex = 13;
            this.tableLayoutPanel1.Controls.Add(this.comboBoxStartSection, 3, 4);
            // 
            // numericUpDownSectionCount
            // 
            this.numericUpDownSectionCount.Dock = System.Windows.Forms.DockStyle.Fill;
            this.numericUpDownSectionCount.Location = new System.Drawing.Point(480, 3);
            this.numericUpDownSectionCount.Name = "numericUpDownSectionCount";
            this.numericUpDownSectionCount.Size = new System.Drawing.Size(267, 25);
            this.numericUpDownSectionCount.TabIndex = 14;
            this.tableLayoutPanel1.Controls.Add(this.numericUpDownSectionCount, 3, 0);
            // 
            // comboBoxSemester
            // 
            this.comboBoxSemester.Dock = System.Windows.Forms.DockStyle.Fill;
            this.comboBoxSemester.FormattingEnabled = true;
            this.comboBoxSemester.Location = new System.Drawing.Point(480, 123);
            this.comboBoxSemester.Name = "comboBoxSemester";
            this.comboBoxSemester.Size = new System.Drawing.Size(267, 23);
            this.comboBoxSemester.TabIndex = 15;
            this.tableLayoutPanel1.Controls.Add(this.comboBoxSemester, 3, 3);
            // 
            // btnSave
            // 
            this.btnSave.Anchor = System.Windows.Forms.AnchorStyles.None;
            this.btnSave.Location = new System.Drawing.Point(200, 320);
            this.btnSave.Name = "btnSave";
            this.btnSave.Size = new System.Drawing.Size(120, 40);
            this.btnSave.TabIndex = 16;
            this.btnSave.Text = "保存";
            this.btnSave.UseVisualStyleBackColor = true;
            this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
            // 
            // btnCancel
            // 
            this.btnCancel.Anchor = System.Windows.Forms.AnchorStyles.None;
            this.btnCancel.Location = new System.Drawing.Point(480, 320);
            this.btnCancel.Name = "btnCancel";
            this.btnCancel.Size = new System.Drawing.Size(120, 40);
            this.btnCancel.TabIndex = 17;
            this.btnCancel.Text = "取消";
            this.btnCancel.UseVisualStyleBackColor = true;
            this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
            // 
            // ScheduleEditForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(800, 450);
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.MaximizeBox = true;
            this.MinimizeBox = true;
            this.FormBorderStyle = FormBorderStyle.Sizable;
            
            // 确保TableLayoutPanel可见并正确布局
            this.tableLayoutPanel1.Dock = DockStyle.Top;
            this.tableLayoutPanel1.Size = new System.Drawing.Size(784, 200);
            
            // 控件添加顺序
            this.Controls.Add(this.tableLayoutPanel1);
            this.Controls.Add(this.btnSave);
            this.Controls.Add(this.btnCancel);
            
            this.Name = "ScheduleEditForm";
            this.Text = "课表编辑";
            ((System.ComponentModel.ISupportInitialize)(this.numericUpDownSectionCount)).EndInit();
            this.tableLayoutPanel1.ResumeLayout(false);
            this.tableLayoutPanel1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();
        }

        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;

        private void btnSave_Click(object? sender, EventArgs e)
        {
            // 验证输入
            if (comboBoxCourse.SelectedItem == null)
            {
                MessageBox.Show("请选择课程", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (comboBoxTeacher.SelectedItem == null)
            {
                MessageBox.Show("请选择教师", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (comboBoxClassroom.SelectedItem == null)
            {
                MessageBox.Show("请选择教室", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (comboBoxDayOfWeek.SelectedItem == null)
            {
                MessageBox.Show("请选择星期", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (comboBoxStartSection.SelectedItem == null)
            {
                MessageBox.Show("请选择开始节次", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (comboBoxSemester.SelectedItem == null)
            {
                MessageBox.Show("请选择学期", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            int courseID = GetSelectedCourseID();
            int teacherID = GetSelectedTeacherID();
            int classroomID = GetSelectedClassroomID();
            string dayOfWeekStr = comboBoxDayOfWeek.SelectedItem?.ToString() ?? "Monday";
            // 将星期字符串转换为枚举
            DayOfWeek dayOfWeekEnum = DayOfWeek.Monday; // 默认值
            
            // 创建中文星期到DayOfWeek枚举的映射
            if (!string.IsNullOrEmpty(dayOfWeekStr))
            {
                switch (dayOfWeekStr)
                {
                    case "星期一":
                        dayOfWeekEnum = DayOfWeek.Monday;
                        break;
                    case "星期二":
                        dayOfWeekEnum = DayOfWeek.Tuesday;
                        break;
                    case "星期三":
                        dayOfWeekEnum = DayOfWeek.Wednesday;
                        break;
                    case "星期四":
                        dayOfWeekEnum = DayOfWeek.Thursday;
                        break;
                    case "星期五":
                        dayOfWeekEnum = DayOfWeek.Friday;
                        break;
                    case "星期六":
                        dayOfWeekEnum = DayOfWeek.Saturday;
                        break;
                    case "星期日":
                        dayOfWeekEnum = DayOfWeek.Sunday;
                        break;
                    default:
                        dayOfWeekEnum = DayOfWeek.Monday; // 默认为周一
                        break;
                }
            }
            int startSection = comboBoxStartSection.SelectedItem != null ? (int)comboBoxStartSection.SelectedItem : 1;
            int sectionCount = (int)numericUpDownSectionCount.Value;
            string semester = comboBoxSemester.SelectedItem?.ToString() ?? "2024-1";

            try
            {
                // 安全检查 - 确保所有必要的参数有效
                if (string.IsNullOrEmpty(semester))
                {
                    MessageBox.Show("请填写完整的课表信息", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 检查时间冲突
                int scheduleID = _isEditMode && _schedule != null ? _schedule.ScheduleID : 0;
                if (_scheduleBLL.CheckTimeConflict(scheduleID, classroomID, dayOfWeekEnum, startSection, sectionCount))
                {
                    MessageBox.Show("所选时间段与已有课表冲突，请重新选择时间或教室", "冲突警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (_isEditMode && _schedule != null)
                {
                    // 更新课表
                    _schedule.CourseID = courseID;
                    _schedule.TeacherID = teacherID;
                    _schedule.ClassroomID = classroomID;
                    _schedule.DayOfWeek = dayOfWeekEnum;
                    _schedule.StartSection = startSection;
                    _schedule.SectionCount = sectionCount;
                    _schedule.Semester = semester;
                    _scheduleBLL.UpdateSchedule(_schedule);
                    MessageBox.Show("课表信息已更新", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    // 添加新课表
                    // 安全创建新课表
                var newSchedule = new Schedule
                {
                    CourseID = courseID,
                    TeacherID = teacherID,
                    ClassroomID = classroomID,
                    DayOfWeek = dayOfWeekEnum,
                    StartSection = startSection,
                    SectionCount = sectionCount,
                    Semester = semester
                };

                    _scheduleBLL.AddSchedule(newSchedule);
                    MessageBox.Show("课表添加成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object? sender, EventArgs e)
        {
            this.Close();
        }

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Label label6;
        private System.Windows.Forms.Label label7;
        private System.Windows.Forms.Label label8;
        private System.Windows.Forms.TextBox txtScheduleID;
        private System.Windows.Forms.ComboBox comboBoxCourse;
        private System.Windows.Forms.ComboBox comboBoxTeacher;
        private System.Windows.Forms.ComboBox comboBoxClassroom;
        private System.Windows.Forms.ComboBox comboBoxDayOfWeek;
        private System.Windows.Forms.ComboBox comboBoxStartSection;
        private System.Windows.Forms.NumericUpDown numericUpDownSectionCount;
        private System.Windows.Forms.ComboBox comboBoxSemester;
        private System.Windows.Forms.Button btnSave;
        private System.Windows.Forms.Button btnCancel;
    }
}